<?php
/**
 * Created by PhpStorm.
 * User: leifei
 * Date: 15/12/25
 * Time: 09:56
 */
namespace Home\Controller;
use Think\Controller;
use Org\Util\Curl;
class WeixinController extends Controller{
    public function _initialize()
    {
        Vendor("WxPayPubHelper.WxPayPubHelper");
        //Vendor("WxPayPubHelper.WxPayJsApiPay");

    }


    public function index(){
        header("Content-type: text/html; charset=utf-8");
        //使用统一支付接口


        $jsJsApi=new \JsApi_pub();
        if($_GET["code"]!=''){
            $jsJsApi->setCode($_GET["code"]);
            $openid = $jsJsApi->GetOpenid();
            $_SESSION['openid']=$openid;


        }else{
            $url=$jsJsApi->createOauthUrlForCode(\WxPayConf_pub::JS_API_CALL_URL);
            header("Location:".$url);
            exit;
        }
        $order_no=date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        $order_price=1;
        $body='羊排';
        $unifiedOrder=new \UnifiedOrder_pub();
        $unifiedOrder->setParameter("openid","$openid");
        $unifiedOrder->setParameter("body","$body");//商品描述
        $unifiedOrder->setParameter("out_trade_no","$order_no");//商户订单号
        $unifiedOrder->setParameter("total_fee",$order_price);//总金额

        $unifiedOrder->setParameter("notify_url",\WxPayConf_pub::NOTIFY_URL);//通知地址
        $unifiedOrder->setParameter("trade_type",'JSAPI');//交易类型


        $prepay_id = $unifiedOrder->getPrepayId();
        if ($prepay_id) {
            $jsJsApi->setPrepayId($prepay_id);
            $jsApiParameters = $jsJsApi->getParameters();
        }
        //获取统一支付接口结果
        $unifiedOrderResult = $unifiedOrder->getResult();


        $this->assign("unifiedOrderResult",$unifiedOrderResult);
        $this->assign("jsApiParameters",$jsApiParameters);
        $this->assign("openid",$_SESSION['openid']);
        $this->display('index');
    }

    public function notify(){


        //使用通用通知接口
        $notify = new \Notify_pub();

        //存储微信的回调
        $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
        $notify->saveData($xml);

        //验证签名，并回应微信。
        //对后台通知交互时，如果微信收到商户的应答不是成功或超时，微信认为通知失败，
        //微信会通过一定的策略（如30分钟共8次）定期重新发起通知，
        //尽可能提高通知的成功率，但微信不保证通知最终能成功。
        // $this->log_result("【checkSign】:\n".$notify->checkSign()."\n");
        if($notify->checkSign() == FALSE){
            $notify->setReturnParameter("return_code","FAIL");//返回状态码
            $notify->setReturnParameter("return_msg","签名失败");//返回信息
        }else{
            $notify->setReturnParameter("return_code","SUCCESS");//设置返回码
        }
        $returnXml = $notify->returnXml();
        echo $returnXml;
        // $this->log_result("【返回回调信息】:\n".$returnXml."\n");
        //==商户根据实际情况设置相应的处理流程，此处仅作举例=======



        if($notify->checkSign() == TRUE)
        {
            if ($notify->data["return_code"] == "FAIL") {
                //此处应该更新一下订单状态，商户自行增删操作
                echo "【通信出错】:\n".$xml."\n";
            }
            elseif($notify->data["result_code"] == "FAIL"){
                //此处应该更新一下订单状态，商户自行增删操作
                echo "【业务出错】:\n".$xml."\n";
            }
            else{
                //此处应该更新一下订单状态，商户自行增删操作
                echo "【支付成功】:\n".$xml."\n";
            }

            //商户自行增加处理流程,
            //例如：更新订单状态
            //例如：数据库操作
            //例如：推送支付完成信息
        }else{
            echo 'Test';
        }
    }


    public function index2(){
        header("Content-type: text/html; charset=utf-8");
        //使用统一支付接口
        $tools = new \JsApiPay();
        $openId = $tools->GetOpenid();

//②、统一下单
        $input = new \WxPayUnifiedOrder();
        $input->SetBody("test");
        $input->SetAttach("test");
        $input->SetOut_trade_no(\WxPayConfig::MCHID.date("YmdHis"));
        $input->SetTotal_fee("1");
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag("test");
        $input->SetNotify_url("http://paysdk.weixin.qq.com/example/notify.php");
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openId);
        $order = \WxPayApi::unifiedOrder($input);
        echo '<font color="#f00"><b>统一下单支付单信息</b></font><br/>';
        var_dump($order);
        $jsApiParameters = $tools->GetJsApiParameters($order);

        $this->assign("unifiedOrderResult",'ccc');
        $this->assign("jsApiParameters",$jsApiParameters);
        $this->assign("openid",$_SESSION['openid']);
        $this->display('index');
    }



}